package com.pay.Service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.pay.Service.AfterCheckTask;
import com.pay.Service.AliPayService;
import com.pay.prjo.AliPayAsyncVo;
import com.pay.prjo.AliPayParam;
import com.pay.prjo.AliPayTemplate;
import com.pay.prjo.TransactionStatus;

import org.springframework.stereotype.Service;

/**  */
@Service
public class AliPayServiceImpl implements AliPayService {
  @Override
  public String pay(AliPayParam param, Integer qrSize) {
    AlipayClient alipayClient =
        new DefaultAlipayClient(
            AliPayTemplate.gatewayUrl,
            AliPayTemplate.appId,
            AliPayTemplate.merchantPrivateKey,
            "json",
            AliPayTemplate.charset,
            AliPayTemplate.alipayPublicKey,
            AliPayTemplate.signType);
    // 2、创建一个支付请求 - 设置请求参数
    AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();
    String returnUrl = param.getReturnUrl();
    if (returnUrl != null) {
      aliPayRequest.setReturnUrl(returnUrl);
    }
    aliPayRequest.setNotifyUrl(param.getNotifyUrl());

    JSONObject bizContent = new JSONObject();
    bizContent.put("out_trade_no", param.getOutTradeNo());
    bizContent.put("total_amount", param.getTotalAmount());
    bizContent.put("subject", param.getSubject());
    bizContent.put("timeout_express", param.getTimeOut());
    bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
    if (qrSize != null) {
      bizContent.put("qr_pay_mode", 4);
      bizContent.put("qrcode_width", qrSize);
    }

    // 会收到支付宝的响应，响应的是一个页面
    aliPayRequest.setBizContent(bizContent.toString());
    try {
      return alipayClient.pageExecute(aliPayRequest).getBody();
    } catch (AlipayApiException e) {
      System.err.println("获取二维码失败");
      e.printStackTrace();
      return null;
    }
  }

  @Override
  public String checkV1(AliPayAsyncVo result, AfterCheckTask ifSuccess, AfterCheckTask ifClosed) {
    if (TransactionStatus.TRADE_SUCCESS.equals(result.getTrade_status())
        || TransactionStatus.TRADE_FINISHED.equals(result.getTrade_status())) {
      // 支付成功
      ifSuccess.doTask();
      return "success";
    } else if (TransactionStatus.TRADE_CLOSED.equals(result.getTrade_status())) {
      ifClosed.doTask();
      return "error";
    }
    return "error";
  }
}
